import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/bean/app_set_info_entity.dart';
import 'package:flutter_app/bean/user_info_entity.dart';
import 'package:flutter_app/manager/AppSetInfoManager.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/network/UrlPath.dart';
import 'package:flutter_app/ui/main/main_view.dart';
import 'package:flutter_app/ui/mine/password_reset/password_reset_view.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:get/get.dart';

import 'login_state.dart';

class LoginLogic extends GetxController {
  final LoginState state = LoginState();

  late TextEditingController userName, password;

  late String telephone = ""; // 手机号码

  @override
  void onInit() {
    super.onInit();
    userName = TextEditingController();
    // userName = TextEditingController(text: 'duchayuan022');
    password = TextEditingController();
    // password = TextEditingController(text: "topnet123");
  }

  @override
  void onReady() {
    super.onReady();
  }

  // 登录
  void login() async {
    if (userName.text.isEmpty) {
      return toast.show("请输入手机号或者账号");
    }

    if (userName.text.isEmpty) {
      return toast.show("请输入密码");
    }

    if (getIsTestId()) {
      UrlPath.baseUrl = "https://xxx.szzfyjzx.icu:5236/";
      // 重新获取配置
      await postAppSetInfo();
    }

    postLogin().then((value) {
      if (value) {
        Get.off(MainPage(title: "首页",));
      }
    });
  }

  // 密码登录接口
  Future<bool> postLogin() async {
    Map<String, dynamic> param = {
      'appCode': UserInfoManager().getAppCode(),
      "platType": 1,
      "loginName": userName.text,
      "loginPassword": password.text,
      "loginType": 1
    };
    ResultData resultData = await Api.login(param);
    if (resultData.isSuccess) {
      state.userInfo = UserInfoEntity.fromJson(resultData.data["data"]);
      if (state.userInfo != null) {
        UserInfoManager().setUserInfo(state.userInfo);
        return true;
      }
      return true;
    }
    toast.show(resultData.data["message"]);
    return false;
  }

  /// 判断是否为测试账号
  bool getIsTestId() {
    if (userName.text == "15038357107") {
      return true;
    }
    return false;
  }

  /// 获取配置信息
  Future<void> postAppSetInfo() async {
    Map<String, dynamic> param = {};
    ResultData resultData = await Api.postAppSetInfo(param);
    if (resultData.isSuccess) {
      AppSetInfoEntity appSetInfoEntity = AppSetInfoEntity.fromJson(resultData.data["data"]);
      AppSetInfoManager().setAppSetInfoEntity(appSetInfoEntity);
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  void goToPasswordResetPage() {
    Get.to(() => PasswordResetPage(title: "忘记密码"));
  }

  @override
  void onClose() {
    super.onClose();
  }
}
